package jfox.platform.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jfox.platform.infrastructure.EntityObject;
import org.jfox.entity.MappedEntity;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * JSON 帮助类，用来将 Entity 生成 JavaScript JSON 对象
 * 在页面上可以通过 $J_JSONUTILS 来访问该类
 *
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 */
public class JSONUtils {

    private final static JSONUtils me = new JSONUtils();

    private JSONUtils() {
    }

    public static JSONUtils getInstance() {
        return me;
    }

    public static JSONResponse createSuccessJSONResponse(Object obj) {
        return JSONResponse.createSuccessJSONResponse(obj);
    }

    public static JSONResponse createFailureJSONResponse(Object obj, Exception e) {
        return JSONResponse.createFailureJSONResponse(obj, e);
    }
    /**
     * 将 Entity 转成 JSON 对象
     */
    public static JSONObject convertEntity(Object entity){
        Map<String, Object> entityMap = new HashMap<String, Object>();
        if(entity == null) {
            return new JSONObject(Collections.EMPTY_MAP);
        }
        else if(entity instanceof EntityObject){
            entityMap.putAll(((EntityObject)entity).convertToMap());
        }
        else if(entity instanceof MappedEntity){
            entityMap.putAll(((MappedEntity)entity).getValueMap());
        }
        else if(entity instanceof Map){
            entityMap.putAll((Map)entity);
        }
        else {
            System.out.println("Not support convert this object to JSONObject: " + entity);
        }
        // 将 ID 和 PARENT_ID 转程 String，以便 JavaScript 能够正确处理
        for (Map.Entry<String, Object> entry : entityMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value != null && (value instanceof Number)) {
                value = value.toString();
                entityMap.put(key, value);
            }
        }
        if(!entityMap.containsKey("id")){
            entityMap.put("id",entityMap.get("ID")); // tree grid 需要 id
        }
        if(!entityMap.containsKey("text") && entityMap.containsKey("NAME")) {
            entityMap.put("text", entityMap.get("NAME")); // tree 需要 text
        }
        return new JSONObject(entityMap);
    }


    /**
     * 将 Entity 列表转成 JSON 字符
     */
    public static JSONArray convertEntities(Collection<?> entities) {
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        if (entities != null && !entities.isEmpty()) {
            for (Object entityObject : entities) {
                if (entityObject instanceof EntityObject) {
                    JSONObject jsonObject = convertEntity((EntityObject)entityObject);
                    jsonObjects.add(jsonObject);
                }
                else if(entityObject instanceof MappedEntity){
                    JSONObject jsonObject = convertEntity((MappedEntity)entityObject);
                    jsonObjects.add(jsonObject);
                }
                else {
                    try {
                        jsonObjects.add(new JSONObject(entityObject.toString()));
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        JSONArray jsonArray = new JSONArray(jsonObjects);
        return jsonArray;
    }


    public static void main(String[] args) {

    }
}
